<?php


namespace GordenSong\Laravel\Templates;


use GordenSong\Laravel\Utils\PathUtil;
use GordenSong\Laravel\Utils\TableMeta;
use Illuminate\Support\Str;

class TableValidatorTemplate extends AbstractTemplate
{
	/** @var string */
	private $table;
	/** @var string */
	private $bladeFile;
	/** @var string */
	private $targetFile;
	/**
	 * @var string|null
	 */
	private $connectionName;

	public function __construct(string $table, string $connectionName = null)
	{
		$this->table = $table;
		$this->connectionName = $connectionName ?? config('database.default');
	}

	public function bladeFile(): string
	{
		if (empty($this->bladeFile)) {
			$php = __DIR__ . '/../../resources/views/table-validator.blade.php';

			$this->bladeFile = PathUtil::crossPlatformPath($php);
		}
		return $this->bladeFile;
	}

	public function targetFile(): string
	{
		if (empty($this->targetFile)) {
			$filename = 'app/Validators/' . Str::studly($this->connectionName) . '/' . Str::studly($this->table) . 'Validator.php';
			$filename = PathUtil::crossPlatformPath($filename);
			$this->targetFile = base_path($filename);
		}
		return $this->targetFile;
	}

	/**
	 * @return array
	 * @throws \Doctrine\DBAL\Schema\SchemaException
	 * @throws \GordenSong\Laravel\Exceptions\TableNotExistException
	 */
	public function getCompiledData(): array
	{
		$tableMeta = TableMeta::make($this->connectionName, $this->table);

		return [
			'namespace' => $tableMeta->getConnectionNamespace(),
			'connection' => $tableMeta->getConnectionName(),
			'classname' => $tableMeta->getClassName(),
			'tablename' => $tableMeta->getTableName(),
			'columns' => $tableMeta->getColumns(),
			'rules' => $tableMeta->getRules(),
			'carbonAt' => $tableMeta->getCarbonAtFields(),
		];
	}
}